import 'dart:io';

import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:photo_view/photo_view.dart';
import 'package:photo_view/photo_view_gallery.dart';
import 'xapp_utils.dart';

/// 图片预览工具
class ImagePreviewUtils {
  static ImagePreviewUtils? _instance;

  static ImagePreviewUtils getInstance() {
    if (_instance == null) {
      _instance = new ImagePreviewUtils._();
    }
    return _instance!;
  }

  ImagePreviewUtils._();

  /// 显示
  /// [images] 图片数组
  /// [heroTag] hero动画tag
  /// [index] 当前索引
  void show({@required List<String>? images, String? heroTag, int index = 0}) {
    var route = MaterialPageRoute(builder: (context) {
      return _ImagePreviewWidget(images!, heroTag: heroTag!, index: index);
    });
    Navigator.of(XAppUtils.getInstance().getContext()).push(route);
  }
}

// 预览widget
class _ImagePreviewWidget extends StatefulWidget {
  final String? heroTag;
  final List<String> images;
  final int index;

  _ImagePreviewWidget(this.images, {this.heroTag, Key? key, this.index = 1})
      : super(key: key);

  @override
  _ImagePreviewWidgetState createState() => _ImagePreviewWidgetState();
}

// 预览widget状态
class _ImagePreviewWidgetState extends State<_ImagePreviewWidget>
    with AutomaticKeepAliveClientMixin {
  PageController? pageController;
  ValueNotifier<int> currentIndex = ValueNotifier(0);

  @override
  void initState() {
    super.initState();
    pageController = PageController(initialPage: widget.index);
    currentIndex.value = widget.index;
  }

  @override
  Widget build(BuildContext context) {
    super.build(context);
    return AnnotatedRegion(
      value: SystemUiOverlayStyle.light,
      child: Scaffold(
        backgroundColor: Colors.black,
        body: SafeArea(
          child: Container(
            width: double.infinity,
            height: double.infinity,
            child: Stack(
              alignment: Alignment.bottomCenter,
              children: <Widget>[
                _buildBody(),
                // 关闭按钮
                Positioned(
                  top: 20,
                  right: 20,
                  child: IconButton(
                    padding: EdgeInsets.all(10),
                    icon: Icon(
                      Icons.close,
                      color: Colors.white,
                      size: 30,
                    ),
                    onPressed: () {
                      Navigator.pop(context);
                    },
                  ),
                ),
                // 索引
                buildIndex(),
              ],
            ),
          ),
        ),
      ),
    );
  }

  // 编译body
  Widget _buildBody() {
    String? heroTag = widget.heroTag;
    return Positioned(
      top: 0,
      left: 0,
      bottom: 0,
      right: 0,
      child: Container(
        child: PhotoViewGallery.builder(
            pageController: pageController,
            itemCount: widget.images.length,
            scrollPhysics: const BouncingScrollPhysics(),
            backgroundDecoration: null,
            enableRotation: true,
            onPageChanged: (i) {
              currentIndex.value = i;
            },
            builder: (BuildContext context, int i) {
              return PhotoViewGalleryPageOptions(
                maxScale: 1.0,
                minScale: 0.1,
                onTapUp: (context, d, c) {
                  Navigator.pop(context);
                },
                imageProvider: _buildImageProvider(widget.images[i]),
                heroAttributes: heroTag != null
                    ? PhotoViewHeroAttributes(tag: heroTag)
                    : null,
              );
            }),
      ),
    );
  }

  ImageProvider<Object> _buildImageProvider(String url) {
    if (url.contains('http')) {
      return NetworkImage(url);
    } else {
      return FileImage(File(url));
    }
  }

  // 编译索引
  Widget buildIndex() {
    if (widget.images.length <= 1) {
      return Text('');
    }

    return Padding(
      padding: EdgeInsets.only(bottom: 20),
      child: ValueListenableBuilder<int>(
        valueListenable: currentIndex,
        builder: (BuildContext context, int page, Widget? child) {
          return Text(
            "${page + 1}/${widget.images.length}",
            style: TextStyle(color: Colors.white70),
          );
        },
      ),
    );
  }

  @override
  bool get wantKeepAlive => true;
}
